/*************************************************
 * HISTORY:                                      *
 *	06/22/2020 pyx : Created.                    *
 *	03/04/2021 pyx : Edited.                     *
=================================================*/

#include "DATransformerFileManager.h"

FileManager::FileManager(std::string workspace) : directory(workspace)
{
}

FileManager::~FileManager()
{
	std::cout << "in ~fm()" << std::endl;
}

//if exist,return 0, else add and return fid
unsigned FileManager::addFile(std::string filepath)
{
	assert(!filepath.empty());

	const auto &iter = filePathSet.find(filepath);
	if (iter != filePathSet.end())
	{
		return 0;
	}
	else
		return getFID(filepath);
}

//if exist,return fid,else add and return fid
unsigned FileManager::getFID(std::string filepath)
{
	assert(!filepath.empty());

	unsigned fid;
	assert(fileIDTable.size() == filePathTable.size());
	if (fileIDTable.count(filepath) == 1)
	{
		fid = fileIDTable[filepath];
		assert(fid > 0);
	}
	else
	{
		fid = fileIDTable.size() + 1;
		filePathSet.insert(filepath);
		fileIDTable[filepath] = fid;
		filePathTable.push_back(filepath); //index = fid-1
		assert(fileIDTable.size() == filePathTable.size());
	}
	return fid;
}


//if exist,return fid,else return 0
unsigned FileManager::getFID_not_add(std::string filepath)
{
	if(filepath.empty()) return 0;

	unsigned fid = 0;
	assert(fileIDTable.size() == filePathTable.size());

	std::cout<<filepath<<std::endl;

	if (fileIDTable.find(filepath) != fileIDTable.end())
	{
		fid = fileIDTable[filepath];
		assert(fid > 0);
	}
	
	return fid;
}

std::string FileManager::getFilePath(unsigned fid)
{
	assert(fid > 0);
	std::string filePath;
	assert(fileIDTable.size() == filePathTable.size());
	if (fid > filePathTable.size())
	{
		std::cout << "INRERNAL ERROR! FID OVERSIZE!"
				  << "\n";
		exit(1);
	}

	filePath = filePathTable[fid - 1]; //index = fid -1
	return filePath;
}

void FileManager::finilize()
{

	Connector *c = new Connector();

	int n;

	n = fileIDTable.size();

	for (const auto &iter : fileIDTable)
	{

		c->insertFile(iter.first, iter.second);
		
	}
	c->commit();

	delete c;
}
